<template>
  <div class="tracking-container">
    <el-card class="tracking-card">
      <h2>Order Tracking</h2>
      
      <div v-if="!orderTracked">
        <el-form :model="trackForm" :rules="rules" ref="trackFormRef" label-width="120px">
          <el-form-item label="Order Number" prop="orderNumber">
            <el-input 
              v-model="trackForm.orderNumber" 
              placeholder="Enter your order number"
              @keyup.enter="trackOrder"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="trackOrder" 
              :loading="tracking"
              style="width: 100%"
            >
              Track Order
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-else-if="orderData">
        <h3>Order Details</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="Order Number">
            {{ orderData.order.orderNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="Status">
            <el-tag 
              :type="getStatusType(orderData.order.orderStatus)" 
              disable-transitions
            >
              {{ orderData.order.orderStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Customer Name">
            {{ orderData.order.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="Delivery Type">
            {{ orderData.order.deliveryType === 'SHIP' ? 'Shipping' : 'Pickup in Store' }}
          </el-descriptions-item>
          <el-descriptions-item label="Created At">
            {{ orderData.order.createdAt }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- Delivery Tracking Timeline -->
        <h3 style="margin-top: 30px;">Delivery Timeline</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(event, index) in deliveryEvents"
            :key="index"
            :timestamp="event.timestamp"
            :color="getTimelineColor(event.status)"
          >
            <el-card>
              <h4>{{ event.status }}</h4>
              <p v-if="event.location">Location: {{ event.location }}</p>
              <p v-if="event.details">{{ event.details }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        
        <el-button @click="resetTracking" style="margin-top: 20px; width: 100%">
          Track Another Order
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { ref, reactive, computed } from 'vue'

export default {
  name: 'OrderTracking',
  setup() {
    const tracking = ref(false)
    const orderTracked = ref(false)
    const orderData = ref(null)
    
    const trackForm = reactive({
      orderNumber: ''
    })
    
    const rules = {
      orderNumber: [
        { required: true, message: 'Please enter order number', trigger: 'blur' }
      ]
    }
    
    const trackOrder = async () => {
      try {
        tracking.value = true
        
        // In a real application, you would make an API call to track the order
        // For now, using a mock implementation
        const response = await mockTrackOrderApi(trackForm.orderNumber)
        
        if (response.success) {
          orderData.value = response
          orderTracked.value = true
          ElMessage.success('Order found!')
        } else {
          ElMessage.error(response.message || 'Order not found')
        }
      } catch (error) {
        console.error('Tracking error:', error)
        ElMessage.error('An error occurred while tracking the order')
      } finally {
        tracking.value = false
      }
    }
    
    const resetTracking = () => {
      orderTracked.value = false
      orderData.value = null
      trackForm.orderNumber = ''
    }
    
    const getStatusType = (status) => {
      switch (status) {
        case 'PENDING': return 'warning'
        case 'CONFIRMED': return 'primary'
        case 'PROCESSING': return 'primary'
        case 'SHIPPED': return 'danger'
        case 'DELIVERED': return 'success'
        case 'CANCELLED': return 'info'
        default: return 'info'
      }
    }
    
    const getTimelineColor = (status) => {
      switch (status) {
        case 'Order Placed': return '#409EFF'
        case 'Processing': return '#409EFF'
        case 'Shipped': return '#F56C6C'
        case 'Out for Delivery': return '#E6A23C'
        case 'Delivered': return '#67C23A'
        case 'Cancelled': return '#909399'
        default: return '#909399'
      }
    }
    
    // Mock API call - in a real app, replace with actual API call
    const mockTrackOrderApi = (orderNumber) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (orderNumber.startsWith('ORD')) {
            resolve({
              success: true,
              order: {
                orderNumber: orderNumber,
                customerName: 'John Doe',
                orderStatus: 'SHIPPED',
                deliveryType: 'SHIP',
                createdAt: '2023-10-15 14:30:00'
              }
            })
          } else {
            resolve({
              success: false,
              message: 'Order not found'
            })
          }
        }, 500)
      })
    }
    
    // Mock delivery events for demonstration
    const deliveryEvents = computed(() => {
      if (!orderData.value) return []
      
      return [
        {
          status: 'Order Placed',
          timestamp: '2023-10-15 14:30',
          details: 'Your order has been placed successfully'
        },
        {
          status: 'Processing',
          timestamp: '2023-10-15 16:45',
          details: 'Your order is being processed'
        },
        {
          status: 'Shipped',
          timestamp: '2023-10-16 09:15',
          location: 'Warehouse A',
          details: 'Your order has been shipped'
        },
        {
          status: 'Out for Delivery',
          timestamp: '2023-10-16 14:30',
          location: 'Local Delivery Hub',
          details: 'Your order is out for delivery'
        }
      ]
    })
    
    return {
      tracking,
      orderTracked,
      orderData,
      trackForm,
      rules,
      trackOrder,
      resetTracking,
      getStatusType,
      getTimelineColor,
      deliveryEvents
    }
  }
}
</script>

<style scoped>
.tracking-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
  min-height: 100vh;
  background-color: #f9f9f9;
}

.tracking-card {
  max-width: 800px;
  width: 100%;
  margin: 20px auto;
}
</style>